package com.coship.vas.dapg.properties;

import java.util.Properties;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class SystemOverridenProperties extends Properties 
{
	private static final long serialVersionUID = -7760565885890301270L;

	private int systemPropertiesMode = PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK;

	public SystemOverridenProperties() {
		super();
	}

	public String getProperty(String key) {
		return resolveProperty(key, null);
	}

	public int getSystemPropertiesMode() {
		return systemPropertiesMode;
	}

	public SystemOverridenProperties(Properties defaults) {
		super(defaults);
	}

	public String getProperty(String key, String defaultValue) {
		return resolveProperty(key, defaultValue);
	}

	public void setSystemPropertiesMode(int systemPropertiesMode) {
		this.systemPropertiesMode = systemPropertiesMode;
	}

	private String resolveProperty(String key, String defaultValue) {
		String propVal = null;
		if (systemPropertiesMode == PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE) {
			propVal = resolveSystemProperty(key);
		}
		if (propVal == null) {
			propVal = super.getProperty(key);
		}
		if (propVal == null
				&& systemPropertiesMode == PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK) {
			propVal = resolveSystemProperty(key);
		}

		if (propVal == null) {
			propVal = defaultValue;
		}

		return propVal;
	}

	private String resolveSystemProperty(String key) {
		try {
			return System.getProperty(key);
		} catch (Throwable ex) {
			System.err.println("Could not access system property '" + key
					+ "': " + ex);
			return null;
		}
	}
}